package com.sa.nfcwriter;

import java.util.Locale;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

	// ToDo: set your locale, or better, get locale from system or ask user
	private static final Locale LOCALE = new Locale("es");

	private EditText url;
	private EditText manufacturer;
	private EditText model;
	private TextView state;
	private NfcAdapter nfcAdapter;
	private PendingIntent pendingIntent;

	public static boolean firstTime = true;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		url = (EditText) findViewById(R.id.urlValue);
		manufacturer = (EditText) findViewById(R.id.manufacturerValue);
		model = (EditText) findViewById(R.id.modelValue);
		//
		state = (TextView) findViewById(R.id.state);

		nfcAdapter = NfcAdapter.getDefaultAdapter(this);
		pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
				getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
	}

	public void onPause() {
		super.onPause();

		if (nfcAdapter != null) {
			nfcAdapter.disableForegroundDispatch(this);
		}
	}

	public void onResume() {
		super.onResume();

		if (nfcAdapter != null) {
			if (nfcAdapter.isEnabled()) {
				nfcAdapter.enableForegroundDispatch(this, pendingIntent, null,
						null);
			} else {

			}
		} else {

		}
	}

	public void onNewIntent(Intent intent) {

		new NfcProcessThread(intent).start();
	}

	public class NfcProcessThread extends Thread {

		private Intent intent;

		public NfcProcessThread(Intent intent) {
			this.intent = intent;
		}

		public void run() {
			Looper.prepare();
			final String action = intent.getAction();

			final NFCWrite nfcIntent = new NFCWrite(intent);

			final String textToWrite = url.getText() + ";"
					+ manufacturer.getText() + ";" + model.getText();

			if (textToWrite.length() > 0) {
				try {
					nfcIntent.write(textToWrite, LOCALE, true);
					runOnUiThread(new Runnable() {
						public void run() {
							try {

								state.setText(getString(R.string.finished));


							} catch (Exception ignored) {
							}
						}
					});
				} catch (Exception e) {

				}
			}
		}

	}

}
